package com.example.javabasic.thread.classone.completion;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.io.IOException;
import java.sql.SQLException;
import java.util.concurrent.*;

/**
 * @description
 * @Author Lin FuYuan
 * @date 2021/2/7
 */
public class CompletionServiceTest {


    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ThreadPoolTaskExecutor executor = getExecutor();
        try {
            test(executor);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("异常");
        }
        System.out.println("执行完壁!!!!!!!!!");
        executor.shutdown();
    }


    public static ThreadPoolTaskExecutor getExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(5);
        //最大线程数
        executor.setMaxPoolSize(5);
        //队列容量
        executor.setQueueCapacity(1000);
        //线程活跃数
        executor.setKeepAliveSeconds(2);
        //线程名字前缀
        executor.setThreadNamePrefix("TETSTTSTST");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //关闭时等待线程执行完成
        executor.setWaitForTasksToCompleteOnShutdown(false);
        executor.initialize();
        return executor;
    }


    public static void test(Executor executor) throws InterruptedException, ExecutionException {
        CompletionService<Boolean> comp = new ExecutorCompletionService(executor);
        for (int i = 0; i < 5; i++) {
            int n = i;
            comp.submit(() -> {
                Thread.sleep(2000);
                System.out.println(n);
                   try {
                       if (n == 4) {
                           String x = null;
                           x.toString();
                           while (true) {
                           }
                       }
                   }catch (Exception e){

                   }
                return true;
            });
        }

        for (int i = 0; i < 5; i++) {
            try {
                Future<Boolean> take = comp.take();
                Boolean aBoolean = take.get();
                System.out.println(aBoolean);
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        System.out.println("执行完壁Test!!!!!!!!!");
    }


}
